package com.hua.ui;

import javax.net.ssl.ExtendedSSLSession;
import javax.swing.*;

import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.*;

import org.apache.http.impl.client.AbstractAuthenticationHandler;

import com.hua.Dao.SqlService;
import com.hua.Model.FileInfo;
import com.hua.Model.PermissInfo;
import com.hua.Model.UserInfo;
import com.hua.Service.funtion;
import com.hua.Service.upload_download;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EventObject;
import java.util.List;

public class ListShow extends JPanel {
	ArrayList<FileInfo> uArray = new ArrayList<>();
	private JPanel contentPane;
	private JTable table;
	private int width = 300, height = 300;
	private ImageIcon image;

	public ListShow(Boolean state, String tip) {
		setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(10, 10, 888, 480);
		add(panel);
		panel.setLayout(null);

		JLabel lblNewLabel = new JLabel("");
		lblNewLabel.setBounds(240, 37, 300, 300);
		panel.add(lblNewLabel);
		image = new ImageIcon("src/main/resources/images/black_task.png");
		Image img = image.getImage();
		img = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
		image.setImage(img);
		lblNewLabel.setIcon(image);

		JButton btnNewButton = new JButton(tip);
		btnNewButton.setBounds(225, 391, 350, 50);
		panel.add(btnNewButton);
	}

	/**
	 * @wbp.parser.constructor
	 */
	public ListShow(List<FileInfo> files, String name, PermissInfo user_permiss, UserInfo user) {
		setLayout(null);
		// System.out.println("filelist更新");
		uArray.clear();
		// 添加所有查询数据
		uArray.addAll(files);

		JPanel panel = new JPanel();
		// 设置边框
		panel.setBorder(new LineBorder(new Color(194, 194, 194), 1));
		panel.setBounds(10, 10, 888, 480);
		add(panel);

		String[] columnNames = new String[] { "内容" };
		Object[][] data = new Object[uArray.size()][1];
		//

		for (int i = 0; i < uArray.size(); i++) {
			final int index = i;
			// 记录面板
			JPanel panel_1 = new JPanel();
			panel_1.setBounds(10, 289, 530, 80);
			add(panel_1);
			panel_1.setLayout(null);

			JLabel lblNewLabel = new JLabel("");
			if (uArray.get(i).getType().equals("photo")) {
				lblNewLabel.setIcon(new ImageIcon("src/main/resources/images/photo.png"));
			} else if (uArray.get(i).getType().equals("document")) {
				lblNewLabel.setIcon(new ImageIcon("src/main/resources/images/document.png"));

			} else if (uArray.get(i).getType().equals("audio")) {
				lblNewLabel.setIcon(new ImageIcon("src/main/resources/images/audio.png"));

			} else if (uArray.get(i).getType().equals("movie")) {
				lblNewLabel.setIcon(new ImageIcon("src/main/resources/images/movie.png"));

			} else {
				lblNewLabel.setIcon(new ImageIcon("src/main/resources/images/more.png"));
			}
			lblNewLabel.setBounds(14, 13, 56, 54);
			panel_1.add(lblNewLabel);

			JLabel lblNewLabel_1 = new JLabel(uArray.get(i).getName());
			lblNewLabel_1.setFont(new Font("Alimama ShuHeiTi", Font.BOLD, 15));
			lblNewLabel_1.setBounds(76, 13, 400, 30);
			lblNewLabel_1.setPreferredSize(new Dimension(-1, lblNewLabel_1.getHeight()));
			panel_1.add(lblNewLabel_1);

			// share 为1则共享
			if (uArray.get(i).getShare() == 1 && uArray.get(index).getUser_key()==user.getId()) {
				JLabel btnNewButton_public = new JLabel("我的分享");
				btnNewButton_public.setOpaque(true); // 设置为不透明，以便显示背景颜色
				btnNewButton_public.setBackground(new Color(253, 94, 43)); // 设置背景颜色为橙色
				btnNewButton_public.setForeground(Color.WHITE); // 设置字体颜色为白色
				btnNewButton_public.setHorizontalAlignment(JLabel.CENTER); // 设置水平居中
				btnNewButton_public.setVerticalAlignment(JLabel.CENTER); // 设置垂直居中
				btnNewButton_public.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置圆角边框
				btnNewButton_public.setBounds(420, 42, 100, 20);
				panel_1.add(btnNewButton_public);
			}else if (uArray.get(i).getShare() == 1 && uArray.get(index).getUser_key()!=user.getId()) {
				JLabel btnNewButton_public = new JLabel("Ta的分享");
				btnNewButton_public.setOpaque(true); // 设置为不透明，以便显示背景颜色
				btnNewButton_public.setBackground(new Color(253, 94, 43)); // 设置背景颜色为橙色
				btnNewButton_public.setForeground(Color.WHITE); // 设置字体颜色为白色
				btnNewButton_public.setHorizontalAlignment(JLabel.CENTER); // 设置水平居中
				btnNewButton_public.setVerticalAlignment(JLabel.CENTER); // 设置垂直居中
				btnNewButton_public.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); // 设置圆角边框
				btnNewButton_public.setBounds(420, 42, 100, 20);
				panel_1.add(btnNewButton_public);
			}

			funtion fun = new funtion(); // 实例化封装类

			JLabel lblNewLabel_2 = new JLabel("上传时间：" + uArray.get(i).getDate());
			lblNewLabel_2.setBounds(76, 44, 240, 18);
			panel_1.add(lblNewLabel_2);
			
			Double size=uArray.get(i).getSize();
			if(size<0.1){
				size=0.1;
			}
			JLabel lblNewLabel_3 = new JLabel("大小：" + size + "MB");
			lblNewLabel_3.setBounds(300, 44, 240, 18);
			lblNewLabel_3.setForeground(new Color(63, 112, 255));
			panel_1.add(lblNewLabel_3);

			JButton btnNewButton = new JButton("下载");
			btnNewButton.setBounds(660, 27, 91, 27);
			panel_1.add(btnNewButton);

			JButton btnNewButton_1 = new JButton("更多");
			btnNewButton_1.setBounds(760, 27, 91, 27);
			panel_1.add(btnNewButton_1);
			//

			btnNewButton.addActionListener(e -> {
				if (user_permiss.getDownload() == 1) {
					// 在这里添加
					System.out.println("下载文件:" + uArray.get(index).getId() + uArray.get(index).getName());
					// 调用下载
					String desktopPath = System.getProperty("user.home") + "\\Desktop\\";
					String downloadPath = desktopPath + uArray.get(index).getName();
					System.out.println(downloadPath);
					new Thread(() -> {
						try {
							if (upload_download.download(user, uArray.get(index).getId(), uArray.get(index).getName(),
									uArray.get(index).getSize(), uArray.get(index).getType())) {
								funtion.tips("下载文件", "下载成功！\n文件保存到:" + downloadPath);

							} else {
								funtion.tips("下载文件", "下载失败！");
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}).start();
				} else {
					funtion.wanr_tips("权限不足", "你无权限下载文件！");
				}
			});
			btnNewButton_1.addActionListener(e -> {	
				JPopupMenu popupMenu = new JPopupMenu();
				JMenuItem deleteItem = new JMenuItem("删除");
				deleteItem.setIcon(new ImageIcon("src/main/resources/images/delete.png"));
				deleteItem.addActionListener(e1 -> {
					// 处理删除操作
					// 判断权限
					if ((user_permiss.getDelete() == 1 && user.getId() == files.get(index).getUser_key())||user.getId()==0) {
						if (funtion.areYouOk_tips("删除", "你确定删除" + uArray.get(index).getName() + "吗?") == 0) {
							fun.delete_file(user.getAccount(), user.getPassword(),
									uArray.get(index).getPath() + uArray.get(index).getName(),Integer.toString(files.get(index).getId()));
							funtion.tips("删除文件", uArray.get(index).getName() + "删除成功!");
						}
					} else {
						funtion.wanr_tips("权限不足", "你无权限删除或者这不是你的文件");
					}
				});
				JMenuItem renameItem = new JMenuItem("重命名");
				renameItem.setIcon(new ImageIcon("src/main/resources/images/rename.png"));
				renameItem.addActionListener(e1 -> {
					// 处理删除操作
					// 判断权限和用户文件判别
					if (user_permiss.getRename() == 1 && user.getId() == files.get(index).getUser_key()) {
						GetStringWindow GetTextwindow = new GetStringWindow("重命名文件", "请输入文件新名称，注意保留后缀哦",
								uArray.get(index).getName());
						GetTextwindow.setVisible(true);
						String result = GetTextwindow.getGetText();
						// 获取返回的值
						if (result != null && !result.equals("") && !funtion.check_str(result, "含特殊")) {
							// 调用修改方法
							System.out.println(result);
							System.out.println(uArray.get(index).getPath() + uArray.get(index).getName());
							fun.rename_file(user.getAccount(), user.getPassword(),
									uArray.get(index).getPath() + uArray.get(index).getName(), result);
							funtion.tips("重命名", "重命名成功!");
						} else if (result != null) {
							funtion.wanr_tips("修改失败", "或许你输入了很奇怪的东西" + result);
						}
					} else {
						funtion.wanr_tips("权限不足", "你无权限重命名或者这不是你的分享");
					}
				});
				JMenuItem shareItem = new JMenuItem("分享");
				shareItem.setIcon(new ImageIcon("src/main/resources/images/share.png"));
				shareItem.addActionListener(e1 -> {
					if (user_permiss.getShare() == 1) {
						// 在这里添加
						String share;
						if (files.get(index).getShare() == 1) {
							if (user_permiss.getWrite() == 1 && user.getId() == files.get(index).getUser_key()) {
								int vok = funtion.areYouOk_tips("分享文件", "确定取消分享" + files.get(index).getName()
										+ "吗?\n所有用户将不再可见可下载该文件哦(ง •_•)ง\n点击否可获取分享文件链接(¬‿¬)");
								if (vok == 0) {
									// 取消分享文件
									SqlService sql = new SqlService();
									sql.update_SQL("Files", "public=0", files.get(index).getId());
								} else if (vok == 1) {
									// 展示分享链接
									GetStringWindow GetTextwindow = new GetStringWindow("分享文件",
											files.get(index).getName(),
											"http://10.157.0.7:6767/download?account=11111111111&token=bcb15f821479b4d5772bd0ca866c00ad5f926e3580720659cc80d39c9d09802a&filesID="
													+ files.get(index).getId());
									GetTextwindow.setVisible(true);
								}
							} else {
								// 展示分享链接
								GetStringWindow GetTextwindow = new GetStringWindow("分享文件",
										"你无权取消分享，但可分享或删除该文件:" + files.get(index).getName(),
										"http://10.157.0.7:6767/download?account=11111111111&token=bcb15f821479b4d5772bd0ca866c00ad5f926e3580720659cc80d39c9d09802a&filesID="
												+ files.get(index).getId());
								GetTextwindow.setVisible(true);
							}
						} else {
							int vok = funtion.areYouOk_tips("分享文件",
									"确定分享" + files.get(index).getName() + "吗?\n所有用户都将可见可下载分享的文件哦<(￣ c￣");
							if (vok == 0) {
								// 分享文件
								SqlService sql = new SqlService();
								sql.update_SQL("Files", "public=1", files.get(index).getId());
								// 展示链接
								GetStringWindow GetTextwindow = new GetStringWindow("分享文件", files.get(index).getName(),
										"http://10.157.0.7:6767/download?account=11111111111&token=bcb15f821479b4d5772bd0ca866c00ad5f926e3580720659cc80d39c9d09802a&filesID="
												+ files.get(index).getId());
								GetTextwindow.setVisible(true);
							}
						}
					} else {
						funtion.wanr_tips("权限不足", "你无权限分享文件！");
					}
				});
				JMenuItem detailItem = new JMenuItem("文件详情");
				detailItem.setIcon(new ImageIcon("src/main/resources/images/detail.png"));
				detailItem.addActionListener(e1 -> {
					String share;
					if (files.get(index).getShare() == 1) {
						share = "已分享";
					} else {
						share = "未分享";
					}
					funtion.tips("文件详情",
							"文件名称: " + files.get(index).getName() + "\n文件路径: " + files.get(index).getUser_key() + "/"
									+ files.get(index).getPath() + "\n上传时间: " + files.get(index).getDate() + "\n文件MD5: "
									+ files.get(index).getMd5() + "\n文件大小: " + files.get(index).getSize() + "MB\n是否分享: "
									+ share);
				});
				JMenuItem AIItem = new JMenuItem("文件解释");
				AIItem.setIcon(new ImageIcon("src/main/resources/images/AI.png"));
				AIItem.addActionListener(e1 -> {
					funtion funtion = new funtion();
					List<String> txtList = Arrays.asList("txt", "md");
					if (user_permiss.getAi() == 1
							&& funtion.isValidFileExtension(files.get(index).getName(), txtList)) {
						// 新线程打开
						new Thread(() -> {
							try {
								// 后台加载中
								String content = funtion.ai_files(user.getAccount(), user.getPassword(),
										Integer.toString(files.get(index).getId()));
								funtion.tips(files.get(index).getName(), content);
							} catch (Exception e2) {
								e2.printStackTrace();
							}
						}).start();
					} else {
						fun.wanr_tips("AI解释", "权限不足或者文件类型非txt，md");
					}
				});
				popupMenu.add(deleteItem);
				popupMenu.add(shareItem);
				popupMenu.add(renameItem);
				popupMenu.add(detailItem);
				popupMenu.add(AIItem);
				popupMenu.show(btnNewButton_1, btnNewButton_1.getWidth() / 2, btnNewButton_1.getHeight() / 2);
			});
			// 添加到Jtable
			data[i][0] = panel_1;
			// 相关事件
		}
		// pop点击事件

		panel.setLayout(null);

		JPanel panel_1 = new JPanel();
		panel_1.setBounds(14, 13, 825, 46);
		panel.add(panel_1);
		panel_1.setLayout(null);

		// 标题
		JLabel lblNewLabel_4 = new JLabel(name);
		lblNewLabel_4.setFont(new Font("Alimama ShuHeiTi", Font.BOLD, 26));
		lblNewLabel_4.setBounds(0, 0, 178, 47);
		panel_1.add(lblNewLabel_4);

		table = new JTable(new DefaultTableModel(data, columnNames) {
			@Override
			public Class<?> getColumnClass(int columnIndex) {
				return getValueAt(0, columnIndex).getClass();
			}
		});
		// 组件的定义
		table.setRowHeight(80);
		table.setTableHeader(null);
		table.setShowGrid(false);
		JScrollPane jsp = new JScrollPane(table);
		jsp.setLocation(1, 353);
		jsp.setSize(886, 126);
		panel.add(jsp);

		// 创建一个 JScrollPane，将 JList 作为参数传入
		JScrollPane scrollPane = new JScrollPane(jsp);
		// 将 JScrollPane 添加到 panel 中
		scrollPane.setBounds(0, 70, 888, 480);
		scrollPane.setBorder(null); // 去除边框
		panel.add(scrollPane);

		// 添加自定义的单元格渲染器
		table.getColumnModel().getColumn(0).setCellRenderer(new ButtonRenderer());
		table.getColumnModel().getColumn(0).setCellEditor(new ButtonCellEditor());

	}

	// 自定义的单元格渲染器
	public class ButtonRenderer extends DefaultTableCellRenderer {
		@Override
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
				int row, int column) {
			if (value instanceof JPanel) {
				return (JPanel) value;
			} else {
				return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			}
		}
	}

	// 覆写编辑器，单击处理事件
	public class ButtonCellEditor extends DefaultCellEditor {
		private Object currentValue;

		public ButtonCellEditor() {
			super(new JTextField()); // 使用文本字段作为编辑器
		}

		@Override
		public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
				int column) {
			currentValue = value;
			if (value instanceof JPanel) {
				return (JPanel) value;
			} else {
				JPanel panel = new JPanel();
				panel.add(new JButton(value.toString()));
				return panel;
			}
		}

		@Override
		public Object getCellEditorValue() {
			return currentValue;
		}

		@Override
		public boolean isCellEditable(EventObject e) {
			return e instanceof MouseEvent && ((MouseEvent) e).getClickCount() == 1;
		}
	}
}
